<template>
  <div>
    <div class="itemTitle itemFlex">
      <div>{{category}}</div>
      <el-button style="margin-top: -10px" type="text" @click="fetchData(category)"><img src="../../../../images/categoryicon.png" height="16" width="16"/></el-button>
    </div>
    <div class="score">
      <span>销售量 <b style="color:#333">{{saleCount/10000 | fmoney}} </b>万件</span>
      <!-- <span>{{category}}</span> -->
      <span>销售额 <b style="color:#333">{{saleAmount/10000 | fmoney}}</b> 万元</span>
    </div>
    <div class="pieColumn">
      <div :id="'pie1' + id" style="height: 160px"></div>
      <div :id="'pie2' + id" style="height: 160px"></div>
    </div>
    <modelDetailDialog :productionId='id' :name="category" :startDate='startDate' :endDate='endDate' :timeRange="timeRange"></modelDetailDialog>
    <el-dialog class="dialogHeaderFont" :title="category + '销售情况'" :visible.sync="dialogVisible" width="100%" top="8vh" style="font-size:14px;">
      <div class="el-dialog-container">
        <div class="itemContainer">
          <div class="itemTitle" style="background-color: #E0E8EF;">
            <span>公司内部销售走势</span>
          </div>
          <div :id="'saleSummaryChart' + id" style="height: 300px"></div>
        </div>
        <div class="sourceContainer">
          <div class="sourceHeader">
            <div class="conditionContainer flex-container space-between">
              <div class="flex-item">
                <div style="line-height: 40px;font-weight: bold">品类参数特性分析</div>
              </div>
              <div class="flex-item">
                <el-select size="small" placeholder="选择参数" v-model="selectedType"
                           style="width: 156px" @change="onPieChange">
                  <el-option v-for="item in specialType" :key="item.specificationId"
                             :label="item.specificationName" :value="item.specificationId">
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
          <div class="priceDetail">
            <div class="">
              <div class="itemTitle">
                <span>{{specName}}销售分析</span>
              </div>
              <div :id="'salePricePie' + id" style="height: 400px;width: 100%;"></div>
            </div>
            <div>
              <div class="itemTitle">
                <span>{{spacData}}产品销量表现</span>
              </div>
              <el-table :data="pageResult" size="mini" style="width: 100%">
                <el-table-column
                  prop="productCode"
                  label="产品型号">
                </el-table-column>
                <el-table-column
                  prop="categoryName"
                  label="所属品类">
                </el-table-column>
                <el-table-column
                  prop="saleCountProportion"
                  :formatter="formatterSet"
                  label="销量在品类占比">
                </el-table-column>
                <el-table-column
                  sortable
                  prop="salesCount"
                  label="销售量(件)">
                </el-table-column>
                <el-table-column
                  sortable
                  prop="averagePrice"
                  label="销售均价(元)">
                </el-table-column>
              </el-table>
              <div class="paginationSet">
                <div class="pagination-container">
                  <div class="toStart" @click="setCurrentPage">首页</div>
                  <el-pagination background layout="prev, pager, next"
                                 @current-change="selectPage" :current-page.sync="currentPage"
                                 :total="dataSet.length">
                  </el-pagination>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import modelDetailDialog from './modelDetailDialog'
  import * as opreate from 'api/getData'
  const dataSolve = new Map([
    ['销售量', (dataSet) => {
      return ('销量：'+ dataSet.data.value+ '万件'+'<br/>'+'同比增长率：'+ dataSet.data.samePeriod +'，'+
        '环比增长率：'+ dataSet.data.ringRatio +'<br/>'+
        '在全品类销量的占比：'+ dataSet.data.proportion +'<br/>')
    }],
    ['销售额', (dataSet) => {
      return ('销额：'+ dataSet.data.value+ '万元'+'<br/>'+'同比增长率：'+ dataSet.data.samePeriod +'，'+
        '环比增长率：'+ dataSet.data.ringRatio +'<br/>'+
        '在全品类销额的占比：'+ dataSet.data.proportion +'<br/>')
    }],
    ['default', () => '']
  ])

  export default {
    name: 'catagory-item',
    components: {
      modelDetailDialog
    },
    data() {
      return ({
        dialogVisible: false,
        dataSet: [],
        specialType:[{ specificationId: 'priceSetMine', specificationName: "价格" }],
        selectedType:'priceSetMine',
        specName:'价格段',
        spacData:"",
        currentPage:1,
        pageResult:[],
        saleSummaryChart: {}
      })
    },
    props: ['timeRange','id','category', 'saleCount', 'saleAmount', 'amountProportion', 'amountRingRatio', 'countProportion', 'saleRingRatio', 'startDate', 'endDate'],
    computed:{
      pieValue(){
        const {amountProportion,countProportion,amountRingRatio,saleRingRatio} = this;
        return {amountProportion,countProportion,amountRingRatio,saleRingRatio};
      }
    },
    mounted() {
      this.darwPieSet(this.pieValue)
    },
    methods: {
      formatterSet(row){
        return Number.isNaN(Number(row.saleCountProportion)) ? '0.00%' : `${(row.saleCountProportion * 100).toFixed(2)}%`
      },
      setCurrentPage(){
        this.currentPage = 1
      },
      selectPage(val){
        this.pageResult = this.dataSet.slice((val-1)*10,val*10)
      },
      darwPieSet({amountProportion = 0, countProportion = 0, amountRingRatio = 0, saleRingRatio = 0}){
        this.myChartPie1 = this.$echarts.init(document.getElementById('pie1'+ this.id))
        this.myChartPie2 = this.$echarts.init(document.getElementById('pie2'+ this.id))
        const optionSet = { // 绘制图表
          series: [{
          name:'访问来源',
          type:'pie',
          radius: ['75%', '90%'],
          hoverAnimation: false,
          avoidLabelOverlap: false,
          label: {
            normal: {
              show: true,
              position: 'center',
              formatter : `销额\n占比：${(parseFloat(amountProportion || 0)*100).toFixed(2)}%\n 环比：{c|${(parseFloat(amountRingRatio || 0)*100).toFixed(2)}%}`,
              color: 'black',
              lineHeight: 16,
              fontSize: 13,
              verticalAlign: 'bottom',
              rich: {
                c: {
                  color: amountRingRatio > 0 ? 'red' : 'green',
                  lineHeight: 16,
                  fontSize: 12
                }
              }
            }
          },
          labelLine: {
            normal: {
              show: false
            }
          },
          data:[
            { value:amountProportion, name:'营业额', itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: '#4cd09b' // 0% 处的颜色
                }, {
                  offset: 1, color: '#3ec4d7' // 100% 处的颜色
                }],
                globalCoord: false // 缺省为 false
              }}},
            { value:100-amountProportion, name:'others', label: { show: false }, itemStyle: {
              color:{
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: '#9393ab' // 0% 处的颜色
                }, {
                  offset: 1, color: '#6c6c80' // 100% 处的颜色
                }],
                globalCoord: false // 缺省为 false
              }
            }}
          ]
      }]
        }

        const optionSet1 = {
          series: [{
          name:'访问来源',
          type:'pie',
          radius: ['75%', '90%'],
          hoverAnimation: false,
          avoidLabelOverlap: false,
          label: {
            normal: {
              show: true,
              position: 'center',
              formatter : `销量\n占比：${(parseFloat(countProportion || 0)*100).toFixed(2)}%\n 环比：{c|${(parseFloat(saleRingRatio || 0)*100).toFixed(2)}%}`,
              color: 'black',
              lineHeight: 16,
              fontSize: 13,
              verticalAlign: 'bottom',
              rich: {
                c: {
                  color: saleRingRatio > 0 ? 'red' : 'green',
                  lineHeight: 16,
                  fontSize: 12
                }
              }
            }
          },
          labelLine: {
            normal: {
              show: false
            }
          },
          data:[
            { value:countProportion, name:'营业额', itemStyle: { color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0, color: '#fc7282' // 0% 处的颜色
                  }, {
                    offset: 1, color: '#feb887' // 100% 处的颜色
                  }],
                  globalCoord: false // 缺省为 false
                }}},
            { value:100-countProportion, name:'others', itemStyle: { color:{
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0, color: '#9393ab' // 0% 处的颜色
                  }, {
                    offset: 1, color: '#6c6c80' // 100% 处的颜色
                  }],
                  globalCoord: false // 缺省为 false
                }}}
          ]
      }]
        }
        this.myChartPie1.clear()
        this.myChartPie2.clear()
        this.myChartPie1.setOption(optionSet);
        this.myChartPie2.setOption(optionSet1);
      },
      fetchData(channel) {
        this.dialogVisible = true
        opreate.getCategoryLine({ channel: channel, num: this.timeRange }).then(res => {
          let tepmSet = res.data || []
          this.saleSummaryChart = this.$echarts.init(document.getElementById('saleSummaryChart'+ this.id))
          let optionSet = {
            legend: {
              data:['销售量','销售额']
            },
            xAxis: {
              type: 'category',
              data: tepmSet.map(item => item.dateTime)
            },
            tooltip:{
              show:true,
              trigger: 'axis',
              formatter:(param) => {
                let [ A = {}, B = {} ] = param
                let textSet = A.name ? `${A.name}<br/>${dataSolve.get(A.seriesName || 'default')(A)}${dataSolve.get(B.seriesName || 'default')(B)}` : null
                return textSet
              }
            },
            yAxis: [{
              name: '销售量（万件）',
              type: 'value'
            }, {
              name: '销售额（万元）',
              type: 'value'
            }],
            series: [{
              name: '销售量',
              type: 'line',
              yAxisIndex: 0,
              smooth:true,
              itemStyle: {
                color: '#B0ACEC'
              },
              data: tepmSet.map(item => {
                return {
                  value:item.saleCount,
                  proportion: item.countProportion,
                  ringRatio: item.saleRingRatio,
                  samePeriod: item.saleYearOnYear
                }
              })
            }, {
              name: '销售额',
              type: 'line',
              smooth:true,
              itemStyle: {
                color: '#9DD6F9'
              },
              yAxisIndex: 1,
              data: tepmSet.map(item => {
                return {
                  value:item.saleAmount,
                  proportion: item.amountProportion,
                  ringRatio: item.amountRingRatio,
                  samePeriod: item.amountYearOnYear
                }
              })
            }]
          };
          this.saleSummaryChart.setOption(optionSet);
      })
        opreate.categorySpecificationList(this.id).then(res => {
          if('200' == res.code){
            this.specialType = [ { specificationId: 'priceSetMine', specificationName: "价格" }, ...res.data ]
            this.onPieChange(this.selectedType)
          }else {
            this.$message.error('参数加载失败，请稍后再试')
          }
        })
      },
      pieDataSet(timeRange){
        opreate.priceSegment({ categoryId: this.id, num: timeRange }).then(res => {
          this.dataSet = res.data[0].salesCountProduct
          this.pageResult = this.dataSet.slice(0,10)
          this.currentPage = 1
          this.spacData = `价格${res.data[0].priceSegment}`
          this.salePricetPie = this.$echarts.init(document.getElementById('salePricePie'+ this.id));
          let pieOptions = {
            avoidLabelOverlap: true,
            series: [{
              name:'销售数据',
              type:'pie',
              radius: '45%',
              selectedMode:'single',
              color:['red','yellow','orange','blue','green'],
              label:{
                normal: {
                  formatter:(param) => {
                    let tempSet = param.data
                    return tempSet ? '{blue|区间: ' + tempSet.name + '元}\n{blue|销量:' + (parseFloat(tempSet.saleCount)/10000).toFixed(2) + '万件; }{blue|' + '占比: ' + (tempSet.value*100).toFixed(2)  + '%}\n' : ''
                  },
                  rich: {
                    blue: {
                      padding: [3, 0, 0, 0],
                      fontSize: 14,
                      align: 'left',
                      color:'#333'
                    }
                  }
                }
              },
              labelLine: {
                normal: {
                  show: true,
                  length: 20,
                  length2: 30
                }
              },
              data: res.data.map((item,index) => ({
                name: item.priceSegment,
                value: item.saleCountProportion ,
                selected: index == 0,
                saleCount: item.salesCount
              }))
            }]
          }
          this.salePricetPie.clear()
          this.salePricetPie.setOption(pieOptions);
          this.salePricetPie.on('click', (params) => {
            res.data.map(item => {
              if(params.name == item.priceSegment) {
                this.dataSet = item.salesCountProduct
                this.pageResult = this.dataSet.slice(0,10)
                this.currentPage = 1
                this.spacData = `价格${item.priceSegment}`
              }
            })
          });
        })
      },
      otherDataSet(categoryName,specificationId, timeRange){
        opreate.getSaleStandard({ categoryName,specificationId, num: timeRange }).then(res => {
          this.dataSet = res.data[0].salesCountProduct
          this.pageResult = this.dataSet.slice(0,10)
          this.currentPage = 1
          this.spacData = `具有“${res.data[0].specificationValue}”`
          this.salePricetPie = this.$echarts.init(document.getElementById('salePricePie'+ this.id));
          let pieOptions = {
            avoidLabelOverlap: true,
            series: [{
              name:'销售数据',
              type:'pie',
              radius: '45%',
              selectedMode:'single',
              color:['red','yellow','orange','blue','green'],
              label: {
                normal: {
                  formatter:(param) => {
                    let tempSet = param.data
                    return tempSet ? '{blue|类型: ' + tempSet.name + '}\n{blue|销量:' + tempSet.saleCount + '件; }{blue|' + '占比: ' + (tempSet.value*100).toFixed(2)  + '%}\n' : ''
                  },
                  rich: {
                    blue: {
                      padding: [3, 0, 0, 0],
                      fontSize: 14,
                      align: 'left',
                      color:'#333'
                    }
                  }
                }
              },
              labelLine: {
                normal: {
                  show: true,
                  length: 20,
                  length2: 30,             
                }
              },
              data: res.data.map((item,index) => ({
                name: item.specificationValue,
                value: item.salesCountProportion.replace('%', ''),
                selected: index == 0,
                saleCount: item.salesCount
              })),
            }]
          }
          this.salePricetPie.clear()
          this.salePricetPie.setOption(pieOptions);
          this.salePricetPie.on('click', (params) => {
            res.data.map(item => {
              if(params.name == item.specificationValue) {
                this.data = item.salesCountProduct
                this.pageResult = this.dataSet.slice(0,10)
                this.currentPage = 1
                this.spacData = `具有“${item.specificationValue}”`
              }
            })
          });
        })
      },
      onPieChange(newVal){
        let tempSet = this.specialType.find(v => v.specificationId == newVal)
        if(tempSet){
          if('priceSetMine' == tempSet.specificationId){
            this.specName = tempSet.specificationName + '段'
            this.pieDataSet(this.timeRange)
          }else {
            this.specName = tempSet.specificationName
            this.otherDataSet(this.category, newVal, this.timeRange)
          }
        }else {
          this.$message.error('参数加载失败，请稍后再试')
        }
      }
    },
    watch:{
      pieValue:{
        handler:function(n,o){
          console.log(n);
          let {amountProportion,countProportion,amountRingRatio,saleRingRatio} = n;
          this.darwPieSet({amountProportion, countProportion, amountRingRatio, saleRingRatio})
        },
        deep:true
      }
    }
  }
</script>

<style scoped lang="less">
	.itemTitle {
		border-bottom: 1px solid #EEEEEE;
		height: 40px;
		line-height: 20px;
		padding: 10px;
    font-weight: bold;
	}
  .sourceHeader{
    margin-bottom: 0;
    margin-top: 10px;
  }
	.itemFlex {
		display: flex;
		justify-content: space-between;
	}
	.score {
    padding: 10px;
    height: 60px;
    overflow: hidden;
    font-weight: bold;
    color: #606266;
	}
	.pieColumn {
		display: flex;
		margin: 0 10px;
	}
	.pieColumn > div {
		flex: 1;
	}
  #saleSummaryChart3{
    background-color: #ffffff;
  }
	.link {
		text-align: center;
		color: #3AAAEC;
		margin: 0 10px;
		border-top: 1px solid #EEEEEE;
		line-height: 30px;
		font-size: 16px;
	}
  .priceDetail {
    display: flex;
    > div {
      flex: 1;
      padding: 10px;
      padding-top: 0;
      flex-basis: 50%;
      background-color: #ffffff;
    }
  }
</style>
